<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" label-width="100px" inline>
      <el-row>
      <el-col :span="21">
        <el-form-item label="店铺名称">
          <el-input v-model="queryParams.cusName" style="width: 280px" clearable placeholder="请输入店铺名称"></el-input>
        </el-form-item>
        <el-form-item label="签约类型">
          <el-select v-model="queryParams.type" clearable>
            <el-option
              v-for="htlx in htlxOptions"
              :key="htlx.dictValue"
              :label="htlx.dictLabel"
              :value="htlx.dictValue"></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="服务类型">-->
<!--          <el-select v-model="queryParams.fwlx" clearable>-->
<!--            <el-option-->
<!--              v-for="fwlx in fwlxOptions"-->
<!--              :key="fwlx.dictValue"-->
<!--              :label="fwlx.dictLabel"-->
<!--              :value="fwlx.dictValue"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="合同到期日">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 280px"></el-date-picker>
        </el-form-item>
        <el-form-item label="合同状态">
          <el-select v-model="queryParams.status" clearable>
            <el-option
              v-for="htzt in htztOptions"
              :key="htzt.dictValue"
              :label="htzt.dictLabel"
              :value="htzt.dictValue"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
      </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" style="margin-bottom:10px">
      <el-col :span="1.5">
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button type="danger" size="mini" icon="el-icon-delete" :disabled="multiple" @click="handleDel">删除</el-button>-->
<!--      </el-col>-->
    </el-row>

    <el-table v-loading="loading" :data="htxxList" ref="htglTable" :summary-method="showSummaryMethod" show-summary @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" fixed></el-table-column>
      <el-table-column label="店铺名称" header-align="center" align="left" prop="cusName" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="签约类型" header-align="center" align="center" width="120" prop="type" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.type=='1'">新签</el-tag>
          <el-tag v-if="scope.row.type=='2'">续费</el-tag>
          <el-tag type="success" v-if="scope.row.type=='3'">断约新签</el-tag>
          <el-tag type="warning" v-if="scope.row.type=='4'">转介绍</el-tag>
          <el-tag type="danger" v-if="scope.row.type=='5'">同客户不同店铺</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="服务类型" header-align="center" align="center" prop="fwlx" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.fwlx=='1'">整店项目</el-tag>
          <el-tag type="success" v-if="scope.row.fwlx=='2'">单车项目</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="到账金额（元）" header-align="center" align="right" prop="money" :formatter="formatMoney" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="开始日期" header-align="center" align="center" width="120" prop="startDate" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="结束日期" header-align="center" align="center" width="120" prop="endDate" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="合同状态" header-align="center" align="center" width="100" prop="status" :formatter="htztFormat" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.status=='0'">未审核</el-tag>
          <el-tag type="success" v-if="scope.row.status=='1'">已审核</el-tag>
          <el-tag type="danger" v-if="scope.row.status=='2'">已到期</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="录入人" header-align="center" align="center" width="120" prop="createBy" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="录入时间" header-align="center" align="center" prop="createTime" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status=='0' && name === scope.row.createBy"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >修改</el-button>
          <el-button
            v-if="scope.row.status=='0' && name === scope.row.createBy"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleSingleDel(scope.row)"
          >删除</el-button>
          <el-button
            v-if="scope.row.status=='0' && (roles.includes('admin') || roles.includes('leader'))"
            size="mini"
            type="text"
            icon="el-icon-coordinate"
            @click="handleConfirm(scope.row)"
          >审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增或编辑合同 -->
    <el-dialog :title="title" :visible.sync="openAgreementDialog" width="950px" append-to-body>
      <el-form :model="agreementForm" ref="agreementForm" :rules="agreementFormRule" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="店铺名称" prop="customId">
              <el-select v-model="agreementForm.customId" :disabled="customIdEditable" filterable @change="changeCustom" placeholder="请选择店铺" style="width: 320px">
                <el-option
                  v-for="custom in customOptions"
                  :label="custom.cusname"
                  :value="custom.id"
                  :key="custom.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="旺旺号" prop="aliww">
              <el-input v-model="agreementForm.aliww" disabled style="width: 320px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="签约类型" prop="type">
              <el-select v-model="agreementForm.type" @change="changeAgreementType" clearable placeholder="请选择签约类型" style="width: 320px">
                <el-option
                  v-for="type in htlxOptions"
                  :key="type.dictValue"
                  :label="type.dictLabel"
                  :value="type.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务类型" prop="fwlx">
              <el-select v-model="agreementForm.fwlx" @change="changeAgreementType" clearable placeholder="请选择服务类型" style="width: 320px">
                <el-option
                  v-for="type in fwlxOptions"
                  :key="type.dictValue"
                  :label="type.dictLabel"
                  :value="type.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="服务内容" prop="remark">
              <el-input type="textarea" v-model="agreementForm.remark" placeholder="请填写服务说明"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="到账金额" prop="money">
              <el-input v-model.number="agreementForm.money" placeholder="请填到账金额" style="width: 320px">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务起止日期" prop="daterange">
              <el-date-picker
                v-model="agreementForm.dateRange"
                type="daterange"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 320px"
                @change="calServiceDays"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务期限">
              <el-input v-model="agreementForm.serviceDays" disabled style="width: 320px">
                <template slot="append">天</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  deleteAgreement, deleteAgreements,
  insertAgreement,
  selectAgreementById,
  selectAgreementList,
  updateAgreement
} from '@/api/agreement/agreement'
import { selectMySignedCustomList } from '@/api/custom/custom'
import { mapGetters } from 'vuex'

export default {
  name: 'Agreement',
  data(){
    return {
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 查询条件
      queryParams: {
        cusName: '',
        type: '',
        endDate1: '',
        endDate2: '',
        status: '',
        // 日期起止
        dateRange: [],
        pageSize: 10,
        pageNum: 0,
      },
      // 合同类型
      htlxOptions: [],
      // 服务类型
      fwlxOptions: [],
      // 合同状态
      htztOptions: [],
      // 显示table加载动画
      loading: false,
      // table数据源
      htxxList: [],
      // 合同列表总数
      total: 0,
      // 弹窗标题
      title: '',
      // 是否打开添加合同弹窗
      openAgreementDialog: false,
      // 合同表单数据
      agreementForm: {
        id: '',
        customId: '',
        aliww: '',
        fwlx: '',
        money: undefined,
        type: '',
        startDate: '',
        serviceDays: undefined,
        endDate: '',
        status: '',
        reason: '',
        remark: '',
        dateRange: []
      },
      // 店铺名称是否可编辑
      customIdEditable: false,
      // 合同表单校验规则
      agreementFormRule: {
        customId: [
          { required: true, message: "店铺名称不能为空", trigger: ['blur', 'change'] }
        ],
        type: [
          { required: true, message: "合同类型不能为空", trigger: ['blur', 'change'] }
        ],
        fwlx: [
          { required: true, message: "服务内容不能为空", trigger: ['blur', 'change'] }
        ],
        money: [
          { required: true, message: "合同金额必须填写", trigger: ['blur', 'change'] }
        ],
        // daterange: [
        //   { required: true, message: "服务起止日期不能为空", trigger: ['blur', 'change'] }
        // ]
      },
      // 客户列表
      customOptions: [],
      // 服务内容选项
      itemOptions: [],
      // 实际服务内容选项
      realItemOptions: []
    }
  },
  computed:{
    ...mapGetters([
      'userid',
      'name',
      'roles'
    ])
  },
  created() {
    /*合同类型下拉框*/
    this.getDicts("agreement_qylx").then(response => {
      this.htlxOptions = response.data;
      console.log('role = ' + JSON.stringify(this.roles))
      if(this.roles.length === 1 && this.roles.includes('operator')){
        this.htlxOptions.splice(0, 1)
      }
    }),
      this.getDicts("agreement_fwlx").then(response => {
        this.fwlxOptions = response.data;
      }),
    this.getDicts("htgl_htzt").then(response => {
      this.htztOptions = response.data;
    }),
    this.getDicts("htgl_items").then(response => {
      this.itemOptions = response.data;
      this.realItemOptions = this.itemOptions
    }),
    this.getCustomList()
    this.getList()
  },
  methods: {
    // 查询合同列表
    getList() {
      var data = this.getParams();
      selectAgreementList(data).then(response => {
        this.htxxList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 组合查询参数
    getParams(){
      let param = {}
      param.cusName = this.queryParams.cusName
      param.type = this.queryParams.type
      param.status = this.queryParams.status
      param.pageSize = this.queryParams.pageSize
      param.pageNum = this.queryParams.pageNum

      if (this.queryParams.dateRange != null && this.queryParams.dateRange != '' && this.queryParams.dateRange.length > 0) {
        param.endDate1 = this.queryParams.dateRange[0];
        param.endDate2 = this.queryParams.dateRange[1];
      } else {
        param.endDate1 = '';
        param.endDate2 = '';
      }
      return param;
    },
    // 查询我的签约客户
    getCustomList() {
      selectMySignedCustomList().then(response => {
        this.customOptions = response.data
      })
    },
    // 查询
    handleQuery() {
      this.getList();
    },
    // 新增合同
    handleAdd() {
      this.title = '新增合同'
      this.customIdEditable = false
      this.openAgreementDialog = true
      this.resetAgreementForm()
    },
    // 重置合同表单
    resetAgreementForm() {
      this.agreementForm = {
        id: '',
        customId: '',
        items: '',
        originalMoney: undefined,
        discountMoney: undefined,
        realMoney: undefined,
        type: '',
        startDate: '',
        endDate: '',
        dateRange: [],
        serviceDays: undefined,
        status: '0',
        remark: ''
      }
      this.resetForm('agreementForm')
    },
    // 批量删除合同
    handleDel() {
      this.$confirm('您已选择' + this.ids.length + '条数据，是否确认删除？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        for(var i = 0; i < this.ids.length; i++) {
          var row = this.htxxList.find(f=>f.id == this.ids[i])
          if(row.status === '1') {
            this.$message.warning('您所选的数据中包含已确认的合同，请检查！')
            return
          }
        }

        deleteAgreements(this.ids).then(response => {
          this.$message.success('合同已删除！')
          this.getList()
        })
      })
    },
    // 勾选合同
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    // 自定义合计
    showSummaryMethod(param) {
      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {
        if(index === 0){
          sums[index] = '合计'
          return
        } else if(index === 4) {
          const values = data.map(item => Number(item[column.property]));
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);

          if(sums[index] === undefined || sums[index] === '' || sums[index] === null){
            sums[index] = "0.00"
          } else {
            sums[index] = sums[index].toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
          }
        }
      })

      return sums
    },
    // 编辑合同
    handleEdit(row) {
      selectAgreementById(row.id).then(response => {
        this.agreementForm = response.data
        //this.agreementForm.dateRange = [this.agreementForm.startDate, this.agreementForm.endDate]
        this.$set(this.agreementForm, 'dateRange', [this.agreementForm.startDate, this.agreementForm.endDate])
        this.initServiceDays()
        this.changeCustom()
        this.customIdEditable = true
        this.title = '修改合同'
        this.openAgreementDialog = true
      })
    },
    // 单个删除合同
    handleSingleDel(row) {
      this.$confirm('是否确认删除该合同？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAgreement(row.id).then(response => {
          this.$message.success('合同已删除！')
          this.getList()
        })
      })
    },
    changeCustom() {
      var custom = this.customOptions.find(f=>f.id == this.agreementForm.customId)
      if(custom != null){
        this.agreementForm.aliww = custom.aliww
      }
    },
    // 提交合同表单
    submitForm() {
      if(this.agreementForm.money <= 0){
        this.$message.warning('到账金额必须大于0！')
        return
      }
      if(this.agreementForm.dateRange == undefined || this.agreementForm.dateRange == null || this.agreementForm.dateRange.length != 2){
        this.$message.warning('请选择服务起止日期！')
        return
      }

      this.agreementForm.startDate = this.agreementForm.dateRange[0]
      this.agreementForm.endDate = this.agreementForm.dateRange[1]

      this.$refs['agreementForm'].validate(valid => {
        if(valid) {
          if(this.agreementForm.id === null || this.agreementForm.id === '') {
            insertAgreement(this.agreementForm).then(response => {
              this.$message.success('新增合同成功！')
              this.resetAgreementForm()
              this.getList()
              this.cancel()
            })
          } else {
            updateAgreement(this.agreementForm).then(response => {
              this.$message.success('修改合同成功！')
              this.resetAgreementForm()
              this.getList()
              this.cancel()
            })
          }
        }
      })
    },
    // 关闭合同表单
    cancel() {
      this.openAgreementDialog = false
      this.resetAgreementForm()
    },
    handleInput(value) {
      this.agreementForm.amount = value
        .replace(/[^\d.]/g, "")
        .replace(/^(\d+)\.(\d\d).*$/, "$1.$2")
        .replace(/^\.*$/g, "")
    },
    // 格式化合同状态
    htztFormat(row) {
      return this.selectDictLabel(this.htztOptions, row.status);
    },
    // 确认合同
    handleConfirm(row) {
      this.$confirm('合同确认后将无法修改和编辑，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data= {}
        data.id = row.id
        data.status = '1'
        updateAgreement(data).then(response => {
          this.$message.success('合同已审核！')
          this.getList()
        })
      })
    },
    // 创建店铺
    handleCreateShop(row) {

    },
    formatMoney(row){
      if(row.money === undefined || row.money === '' || row.money === null){
        return '0.00'
      } else {
        return row.money.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
      }
    },
    formatDiscountMoney(row){
      if(row.discountMoney === undefined || row.discountMoney === ''){
        return '0.00'
      } else {
        return row.discountMoney.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
      }
    },
    formatRealMoney(row){
      if(row.realMoney === undefined || row.realMoney === ''){
        return '0.00'
      } else {
        return row.realMoney.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
      }
    },
    changeAgreementType(){
      if(this.agreementForm.type === '1'){
        this.realItemOptions = this.itemOptions.filter(f => f.dictValue.charAt(0)==='1' || f.dictValue.charAt(0)==='3')
      } else if(this.agreementForm.type === '2'){
        this.realItemOptions = this.itemOptions.filter(f => f.dictValue.charAt(0)==='2' || f.dictValue.charAt(0)==='3')
      }
    },
    calRealMoney(){
      if(this.agreementForm.originalMoney === undefined || this.agreementForm.originalMoney === '') return
      if(this.agreementForm.discountMoney === undefined || this.agreementForm.discountMoney === '') {
        this.agreementForm.realMoney = this.agreementForm.originalMoney
      } else{
        if(this.agreementForm.discountMoney > this.agreementForm.originalMoney){
          this.$message.warning('折扣金额不能超过合同金额！')
          this.agreementForm.discountMoney = undefined
          return
        }

        this.agreementForm.realMoney = this.agreementForm.originalMoney - this.agreementForm.discountMoney;
      }
    },
    initServiceDays() {
      let start = new Date(this.agreementForm.startDate);
      let end = new Date(this.agreementForm.endDate);

      if(end <= start){
        this.$message.warning('服务截止日期必须大于服务开始日期！')
        this.agreementForm.dateRange = []
        return
      }

      let timeDiff = Math.abs(end - start) + 1
      this.agreementForm.serviceDays = Math.ceil(timeDiff / (1000 * 3600 * 24))
    },
    calServiceDays() {
      let start = new Date(this.agreementForm.dateRange[0]);
      let end = new Date(this.agreementForm.dateRange[1]);

      if(end <= start){
        this.$message.warning('服务截止日期必须大于服务开始日期！')
        this.agreementForm.dateRange = []
        return
      }

      let timeDiff = Math.abs(end - start) + 1
      this.agreementForm.serviceDays = Math.ceil(timeDiff / (1000 * 3600 * 24))
    }
  }
}
</script>

<style scoped lang="scss">

</style>
